package tester;

import tester.Comparator;

import java.io.*;

/**
 * Check two inputStream to see if they are consistent to each other.
 * This method is a tolerant method, it ignore a SPACE characters at the
 * end of each line or a EMPTY_LINE at the end of the stream.
 * Programmer usually output in the way: System.out.println(a[i] + " ");
 * It can cause the trail of each line a extra " ", So is the empty line
 * at the end of a steam.
 */
public class TolerantComparator implements Comparator {
  public int compare(File inputFile, InputStream stdout,
                     InputStream userOutput,
                     Person person, Problem problem) {
    BufferedReader brStandard =
        new BufferedReader(new InputStreamReader(stdout));
    BufferedReader brUserOutput =
        new BufferedReader(new InputStreamReader(userOutput));

    // Compare every line
    String s1, s2;
    try {
      s1 = brStandard.readLine();
      s2 = brUserOutput.readLine();
      while (s1 != null && s2 != null) {
        if (!consistent(s1, s2)) return 0;
        s1 = brStandard.readLine();
        s2 = brUserOutput.readLine();
      }
      if (s1 != null || s2 != null) {
        if (s1 != null) {
          if (s1.length() != 0) return 0;
          s1 = brStandard.readLine();
          if (s1 != null) return 0;
        }
        if (s2 != null) {
          if (s2.length() != 0) return 0;
          s2 = brUserOutput.readLine();
          if (s2 != null) return 0;
        }
      }
    } catch (IOException e) {
      // return 0 when IOException occurs.
      return 0;
    }
    return 100;
  }

  private boolean consistent(String s1, String s2) {
    int len1 = s1.length(), len2 = s2.length();
    int len = len1 < len2 ? len1 : len2;
    // only 1-char's different is allowed
    if (len2 > len1 + 1 || len1 > len2 + 1) return false;
    for (int i = 0; i < len; i++) {
      if (s1.charAt(i) != s2.charAt(i)) return false;
    }
    if (len1 > len2 && s1.charAt(len1 - 1) != ' ' ||
        len1 < len2 && s2.charAt(len2 - 1) != ' ') return false;
    return true;
  }
}
